package com.aishua.fire.controller.activiti;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.aishua.fire.common.JsonArrayResult;
import com.aishua.fire.common.JsonObjectResult;
import com.aishua.fire.common.anno.ModuleService;
import com.aishua.fire.common.constant.BigMenuConstants;
import com.aishua.fire.common.constant.ModuleConstants;
import com.aishua.fire.controller.LoginController;
import com.aishua.fire.entity.activiti.SignTaskListInfo;
import com.aishua.fire.entity.activiti.WorkFlowInfo;
import com.aishua.fire.entity.activiti.YuAnActivitiDetailsRespInfo;
import com.aishua.fire.entity.activiti.YuAnProcessReqInfo;
import com.aishua.fire.entity.activiti.YuAnWorkFlowStartInfo;
import com.aishua.fire.entity.activiti.YuAnWorkFlowStartParm;
import com.aishua.fire.entity.emergencyPre.PositionRespInfo;
import com.aishua.fire.mapper.EmergencyPreMapper;
import com.aishua.fire.service.EmergencyPreManagerService;
import com.aishua.fire.service.LoginService;
import com.aishua.fire.service.OrganizationService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(value = "工作流操作相关", tags = { "工作流操作相关接口" })
@RestController
public class StartPlanController {

	@Autowired
	private TaskService taskService;

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private EmergencyPreManagerService emergencyPreService;

	@Autowired
	private EmergencyPreMapper emergencyPreMapper;

	@Autowired
	private OrganizationService organizationService;

	@Autowired
	private LoginController loginController;

	@ApiOperation(value = "查询工作台任务")
	@GetMapping(value = { "/workFlow" })
	public ResponseEntity<JsonArrayResult<WorkFlowInfo>> getWorkFlow() {
		List<WorkFlowInfo> list = new ArrayList<WorkFlowInfo>();
		WorkFlowInfo searchList = emergencyPreService.getWorkFlow();
		list.add(searchList);
		JsonArrayResult<WorkFlowInfo> r = JsonArrayResult.makeSuccessResult(list, list.size());
		;
		return ResponseEntity.ok(r);
	}

	@ApiOperation(value = "工作台_查看预案详情")
	@GetMapping(value = { "/workFlow/details" })
	public ResponseEntity<JsonArrayResult<YuAnActivitiDetailsRespInfo>> getWorkFlowDetails(
			@RequestParam(name = "pre_id") String pre_id) {

	List<YuAnActivitiDetailsRespInfo> searchList = emergencyPreService.getWorkFlowDetails(pre_id);

	JsonArrayResult<YuAnActivitiDetailsRespInfo> r = JsonArrayResult.makeSuccessResult(searchList, 1);
		return ResponseEntity.ok(r);
	}

	/*
	 * @ApiOperation(value = "查询预案流程人员信息")
	 * 
	 * @GetMapping(value = { "/process" }) public
	 * ResponseEntity<JsonArrayResult<YuanProcessInfo>>
	 * getYuanProcessInfo(@RequestParam(name = "pre_id") String pre_id){
	 * YuanProcessInfo processInfo =emergencyPreService.getYuanProcessInfo(pre_id);
	 * List<YuanProcessInfo> yuanProcessInfo =new ArrayList<YuanProcessInfo>();
	 * yuanProcessInfo.add(processInfo); JsonArrayResult<YuanProcessInfo>
	 * r=JsonArrayResult.makeSuccessResult(yuanProcessInfo,yuanProcessInfo.size());;
	 * return ResponseEntity.ok(r); }
	 */

	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "编辑预案流程人员信息")
	@PostMapping(value = { "/process" })
	public ResponseEntity<JsonObjectResult> editorYuanProcessInfo(@RequestBody @Valid YuAnProcessReqInfo preInfo) {
		YuAnProcessReqInfo yuAnProcessReqInfo = emergencyPreService.editorYuanProcessInfo(preInfo);
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(yuAnProcessReqInfo);
		return ResponseEntity.ok(r);
	}

	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "启动预案工作流")
	@PostMapping(value = { "/stratworkFlow" })
	public ResponseEntity<JsonObjectResult> satrtYuan(@RequestBody @Valid YuAnWorkFlowStartParm info,
			ServletRequest servletRequest) 
	{
	    //插入预案启动选择的预案启动参数  
	    emergencyPreService.insertStartWorkFlowParm(info);

		// 查询当前账号用户id
		String user_id = loginController.getr_idWitha_id(servletRequest);

		// 根据当前账号查看所属部门id
		List<String> r_id = organizationService.getr_idWitha_id(user_id + "");
		// 根据预案id查询部门id
		YuAnWorkFlowStartInfo preInfo = emergencyPreService.getDepartMentId(info.getId());

		if (!r_id.contains(preInfo.getDepartment_id())) {
			JsonObjectResult r = JsonObjectResult.makeSuccessResult("没有权限启动预案");
			return ResponseEntity.ok(r);
		}
		// 查询第二步审批人
		YuAnProcessReqInfo yuAnProcessReqInfo = emergencyPreService.getStepTwoInfo();

		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("pre_name", preInfo.getPre_name());
		// variables.put("iss_time",preInfo.getIss_time());
		variables.put("state", preInfo.getState());
		variables.put("operator", yuAnProcessReqInfo.getStepTwoInfo());
		variables.put("pre_id", info.getId());
		log.info("预案id:{}", info.getId());
		ProcessInstance pi = runtimeService.startProcessInstanceByKey("plan", yuAnProcessReqInfo.getStepTwoInfo(),
				variables);
		// 启动预案修改状态为2:等待中
		emergencyPreService.startEmergencyState(info.getId());
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(null);
		return ResponseEntity.ok(r);
	}

	@ApiOperation(value = "查询预案申请领导人的任务列表")
	@ModuleService(totalModule = BigMenuConstants.emergencyPre, moduleName = ModuleConstants.ENERGENCYPRE)
	@GetMapping(value = { "/leadPlanTaskList" })
	public ResponseEntity<JsonArrayResult<TaskListInfo>> getPlanTaskList(ServletRequest servletRequest) {

		// 根据当前账号查看所属部门id
		String user_id = loginController.getr_idWitha_id(servletRequest);

		// 根据当前账号查看所属部门id
		List<String> r_id = organizationService.getr_idWitha_id(user_id + "");

		// 查询第二步审批人
		YuAnProcessReqInfo yuAnProcessReqInfo = emergencyPreService.getStepTwoInfo();

		if (!r_id.contains(yuAnProcessReqInfo)) {
			return null;
		}

		List<TaskListInfo> infos = new ArrayList<TaskListInfo>();
		List<Task> taskList = taskService.createTaskQuery().includeProcessVariables().processDefinitionKey("plan")// 根据流程定义key查询
				.taskAssignee(user_id)// 根据办理人查询
				.orderByTaskCreateTime().desc().list();
		for (Task task : taskList) {
			Map<String, Object> vars = task.getProcessVariables();
			TaskListInfo info = new TaskListInfo();
			// info.setIss_time((String)vars.get("iss_time"));
			info.setPre_name((String) vars.get("pre_name"));
			info.setState((String) vars.get("state"));
			info.setOperator((String) vars.get("operator"));
			info.setPre_id((String) vars.get("pre_id"));
			info.setTask_id(task.getId());

			infos.add(info);
		}
		JsonArrayResult<TaskListInfo> r = JsonArrayResult.makeSuccessResult(infos, infos.size());
		return ResponseEntity.ok(r);
	}

	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "预案申请领导人是否同意启动预案:1同意,0不同意")
	@GetMapping(value = { "/completeYuAnTask" })
	public ResponseEntity<JsonObjectResult> completeYuAnTask(@RequestParam(name = "taskId") String taskId,
			@RequestParam(name = "pre_id") String pre_id, @RequestParam(name = "isAgree") int isAgree,
			ServletRequest servletRequest) {

		// 根据当前账号查看所属部门id
		String user_id = loginController.getr_idWitha_id(servletRequest);

		// 根据当前账号查看所属部门id
		List<String> r_id = organizationService.getr_idWitha_id(user_id + "");

		// 查询第二步审批人
		YuAnProcessReqInfo yuAnProcessReqInfo = emergencyPreService.getStepTwoInfo();

		if (!r_id.contains(yuAnProcessReqInfo)) {
			JsonObjectResult r = JsonObjectResult.makeSuccessResult("没有权限");
			return ResponseEntity.ok(r);
		}

		// 根据预案id查询
		List<PositionRespInfo> positionInfos = emergencyPreMapper.getPosition(pre_id);
		log.info("签到人信息:{}", positionInfos);
		Map<String, Object> variables = taskService.getVariables(taskId);
		/*
		 * for(PositionRespInfo info : positionInfo) { PositionRespInfo positionRespInfo
		 * = new PositionRespInfo(); positionRespInfo.setPre_id(pre_id);
		 * positionRespInfo.setPosition(position); vars.put("pre_id",info.getPre_id() );
		 * vars.put("position",info.getPosition()); vars.put("num",info.getNum());
		 * vars.put("content", info.getContent());
		 * 
		 * }
		 */
		variables.put("ss", positionInfos);
		// isAgree > 0 同意,否则驳回
		variables.put("isAgree", isAgree);
		String sb = "";
		for (int i = 0; i < positionInfos.size(); i++) {
			if (positionInfos.size() - 1 == i) {
				sb += positionInfos.get(i).getPosition_id();
			} else {
				sb += positionInfos.get(i).getPosition_id() + ",";
			}
			// userIds.add(positionInfo.getPosition_id());
			// log.info("Position_id:{}",positionInfo.getPosition_id());
		}
		variables.put("rtty", sb);

		taskService.setVariables(taskId, variables);
		taskService.complete(taskId);
		// 完成任务 设置签到步骤
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(null);
		return ResponseEntity.ok(r);
	}

	@ApiOperation(value = "查询签到人的任务列表")
	@ModuleService(totalModule = BigMenuConstants.emergencyPre, moduleName = ModuleConstants.ENERGENCYPRE)
	@GetMapping(value = { "/signPlanTaskList" })
	public ResponseEntity<JsonArrayResult<SignTaskListInfo>> getsignPlanTaskList(
			@RequestParam(name = "user_id") String user_id) {

		List<SignTaskListInfo> signInfo = new ArrayList<SignTaskListInfo>();
		// SignTaskListInfo signTaskListInfo = new SignTaskListInfo();
		// SignTaskListInfo info = new SignTaskListInfo();
		List<Task> taskList = taskService.createTaskQuery().includeProcessVariables().processDefinitionKey("plan")// 根据流程定义key查询
				.taskCandidateUser(user_id)// taskAssignee(user_id)//根据办理人查询
				.orderByTaskCreateTime().desc().list();
		for (Task task : taskList) {
			Map<String, Object> vars = task.getProcessVariables();

			// signTaskListInfo.setTask_id(task.getId());
			log.info("任务id:{}", task.getId());
			// signTaskListInfo.setPre_id((String)vars.get("pre_id"));
			// signTaskListInfo.setOperator((String)vars.get("operator"));

			// //根据预案id 用户id查询用户详细
			List<SignTaskListInfo> infos = emergencyPreService.getPositionWithTask((String) vars.get("pre_id"),
					user_id);
			for (SignTaskListInfo info : infos) {
				// info.setContent(info.getContent());
				// info.setNum(info.getNum());
				info.setOperator((String) vars.get("operator"));
				info.setPre_id((String) vars.get("pre_id"));
				info.setTask_id(task.getId());
				signInfo.add(info);
			}

		}
		JsonArrayResult<SignTaskListInfo> r = JsonArrayResult.makeSuccessResult(signInfo, signInfo.size());
		return ResponseEntity.ok(r);
	}

	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "签到人完成签到")
	@GetMapping(value = { "/signYuAnTask" })
	public ResponseEntity<JsonObjectResult> signcompleteYuAnTask(@RequestParam(name = "taskId") String taskId,
			@RequestParam(name = "pre_id") String pre_id, @RequestParam(name = "position_id") String position_id) {

		// 更新签到人状态
		emergencyPreService.updateSignStat(pre_id, position_id);
		// 查询所有人是否签到
		boolean b = emergencyPreService.selectAllSignState(pre_id);
		if (b) {
			log.info("所有人完成签到");
			// 完成任务 设置签到步骤
			taskService.complete(taskId);

		}
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(null);
		return ResponseEntity.ok(r);
	}

	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "申请结束预案")
	@GetMapping(value = { "/endYuAnTask" })
	public ResponseEntity<JsonObjectResult> jishuYuAnTask(@RequestParam(name = "taskId") String taskId,@RequestParam(name = "pre_id") String pre_id,
			ServletRequest servletRequest) {
		// 查询当前账号用户id
		String user_id = loginController.getr_idWitha_id(servletRequest);

		// 根据当前账号查看所属部门id
		List<String> r_id = organizationService.getr_idWitha_id(user_id + "");
		
		// 根据预案id查询部门id
		YuAnWorkFlowStartInfo preInfo = emergencyPreService.getDepartMentId(pre_id);

		if (!r_id.contains(preInfo.getDepartment_id())) {
			JsonObjectResult r = JsonObjectResult.makeSuccessResult("没有权限结束预案");
			return ResponseEntity.ok(r);
		}
		taskService.complete(taskId);
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(null);
		return ResponseEntity.ok(r);
	}

	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "预案申请领导人是否同意结束:1同意,0不同意")
	@GetMapping(value = { "/ifendYuAnTask" })
	public ResponseEntity<JsonObjectResult> endYuAnTask(@RequestParam(name = "taskId") String taskId,
			@RequestParam(name = "pre_id") String pre_id, @RequestParam(name = "isAgree") int isAgree) {
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("isAgree", isAgree);
		taskService.complete(taskId, variables);
		// 完成任务 设置签到步骤
		if (isAgree == 1) {
			// 更新预案状态
			emergencyPreService.endEergencyState(pre_id);
		}
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(null);
		return ResponseEntity.ok(r);
	}

}
